package com.example.test2.activity;

import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;

import com.example.test2.R;
import com.example.test2.databinding.ActivityEditPwdBinding;
import com.example.test2.db.control.UserDbController;
import com.example.test2.db.entity.User;
import com.example.test2.http.Constants;
import com.example.test2.utils.ToastUtils;

public class EditPwdActivity extends BaseActivity<ActivityEditPwdBinding>{
    private UserDbController dbUserController;
    private User user;
    private String pwd;

    @Override
    protected void initData() {
        super.initData();
        getBinding().titleBar.setTitle("修改密码");
        dbUserController = UserDbController.getInstance(this);
        user = dbUserController.searchByName(Constants.PHONE);
        pwd = user.getPwd();

}
    @Override
    protected void initClick() {
        super.initClick();
        getBinding().titleBar.setLeftIconOnClickListener(v -> {
            finish();
        });
        getBinding().btCommit.setOnClickListener(v -> {
            commit();
        });
    }

    private void commit() {
        String oPwd = getBinding().etOld.getText().toString();
        String nPwd = getBinding().etNew.getText().toString();
        String cPwd = getBinding().etPwd.getText().toString();

        if (TextUtils.isEmpty(cPwd) || TextUtils.isEmpty(nPwd) || TextUtils.isEmpty(oPwd)) {
            ToastUtils.getInstance().show(this, "密码不能为空");
            return;
        }

        if (!pwd.equals(oPwd)) {
            ToastUtils.getInstance().show(this, "旧密码错误");
            return;
        }
        if (!nPwd.equals(cPwd)) {
            ToastUtils.getInstance().show(this, "新密码不一致");
            return;
        }
        user.setPwd(nPwd);
        dbUserController.update(user);
        ToastUtils.getInstance().show(this, "修改成功");
        new Handler().postDelayed(() -> {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }, 500);

    }

    @Override
    protected int initLayout() {
        return R.layout.activity_edit_pwd;
    }

    @Override
    protected ActivityEditPwdBinding onCreateViewBinding(@NonNull LayoutInflater layoutInflater) {
        return ActivityEditPwdBinding.inflate(layoutInflater);
    }
}

